
const ticketCreateController = function(HttpService, $state, StorageService, KindEditorService) {
  'ngInject';

  const vm = this;

  // 工单数据
  vm.ticket = {
    title: '',
    description: '',
    source_url: '',
    source_type: 'web',
    resolution: '',
    location: '',
    ci_item_id: null,
    product_id: null,
    product_module_id: null,
    application_id: null,
    module_id: null,
    product_category_id: null,
    incident_level: 'medium',
    impact_scope: 'individual',
    urgency: 'medium',
    business_impact: '',
    workaround: '',
    ticket_type: 'incident',
    priority: 'medium',
    category: '',
    support_staff_id: null,
    due_date: '',
    estimated_hours: null,
    tags: []
  };

  // 选项数据
  vm.options = {
    applications: [],
    modules: {},
    productCategories: [],
    tags: [],
    supportStaff: [],
    solutionTemplates: [],
    ciItems: [],
    products: [],
    productModules: {},
    enums: {}
  };

  // 界面状态
  vm.isLoading = false;
  vm.isLoadingOptions = true;
  vm.activeTab = 'basic'; // basic, technical, advanced
  vm.availableModules = [];
  vm.availableProductModules = [];
  vm.tagInput = '';
  vm.selectedTags = [];

  // KindEditor 配置
  vm.descriptionEditorOptions = KindEditorService.presets.full;
  vm.resolutionEditorOptions = angular.extend({}, KindEditorService.presets.full, {
    height: '250px'
  });

  // 初始化
  vm.$onInit = function() {
    loadTicketOptions();
    loadDraftData();
  };

  // 加载工单选项数据
  function loadTicketOptions() {
    // 并行加载多个选项数据
    const promises = [
      HttpService.get('/tickets/options'),
      HttpService.ciItems.list({ status: 'active', limit: 100 }),
      HttpService.products.list({ status: 1, limit: 50 }),
      HttpService.productCategories.list({ status: 1 }),
      HttpService.productModules.list({ status: 1, limit: 200 })
    ];
    
    Promise.all(promises)
      .then(responses => {
        // 处理原有的工单选项
        if (responses[0].success) {
          vm.options = angular.extend(vm.options, responses[0].data);
        }
        
        // 处理CI项目数据
        if (responses[1].success) {
          vm.options.ciItems = responses[1].data;
        }
        
        // 处理产品数据
        if (responses[2].success) {
          vm.options.products = responses[2].data;
        }
        
        // 处理产品分类数据
        if (responses[3].success) {
          vm.options.productCategories = responses[3].data;
        }
        
        // 处理产品模块数据
        if (responses[4].success) {
          const modulesByProduct = {};
          responses[4].data.forEach(module => {
            if (!modulesByProduct[module.product_id]) {
              modulesByProduct[module.product_id] = [];
            }
            modulesByProduct[module.product_id].push(module);
          });
          vm.options.productModules = modulesByProduct;
        }
        
        vm.updateAvailableModules();
        vm.updateAvailableProductModules();
      })
      .catch(error => {
        console.error('加载工单选项失败:', error);
        alert('加载选项数据失败，请刷新页面重试');
      })
      .finally(() => {
        vm.isLoadingOptions = false;
      });
  }

  // 加载草稿数据
  function loadDraftData() {
    const draftData = StorageService.session.get('ticketDraft');
    if (draftData) {
      vm.ticket = angular.extend(vm.ticket, draftData);
      vm.selectedTags = vm.ticket.tags || [];
      vm.updateAvailableModules();
    }
  }

  // 保存草稿数据
  function saveDraftData() {
    vm.ticket.tags = vm.selectedTags;
    StorageService.session.set('ticketDraft', vm.ticket);
  }

  // 清除草稿数据
  function clearDraftData() {
    StorageService.session.remove('ticketDraft');
  }

  // 界面控制方法
  vm.setActiveTab = function(tab) {
    vm.activeTab = tab;
    saveDraftData(); // 切换tab时保存草稿
  };

  vm.updateAvailableModules = function() {
    if (vm.ticket.application_id && vm.options.modules[vm.ticket.application_id]) {
      vm.availableModules = vm.options.modules[vm.ticket.application_id];
    } else {
      vm.availableModules = [];
    }
    
    // 如果当前选择的模块不在可用模ules列表中，清空选择
    if (vm.ticket.module_id && !vm.availableModules.find(m => m.id == vm.ticket.module_id)) {
      vm.ticket.module_id = null;
    }
  };
  
  // 新增：更新可用的产品模块
  vm.updateAvailableProductModules = function() {
    if (vm.ticket.product_id && vm.options.productModules[vm.ticket.product_id]) {
      vm.availableProductModules = vm.options.productModules[vm.ticket.product_id];
    } else {
      vm.availableProductModules = [];
    }
    
    // 如果当前选择的产品模块不在可用列表中，清空选择
    if (vm.ticket.product_module_id && !vm.availableProductModules.find(m => m.id == vm.ticket.product_module_id)) {
      vm.ticket.product_module_id = null;
    }
  };

  // 标签管理
  vm.addTag = function() {
    if (!vm.tagInput || vm.tagInput.trim() === '') return;
    
    const tagName = vm.tagInput.trim();
    if (vm.selectedTags.indexOf(tagName) === -1) {
      vm.selectedTags.push(tagName);
      vm.tagInput = '';
    }
  };

  vm.removeTag = function(index) {
    vm.selectedTags.splice(index, 1);
  };

  vm.selectExistingTag = function(tag) {
    if (vm.selectedTags.indexOf(tag.name) === -1) {
      vm.selectedTags.push(tag.name);
    }
  };

  // 应用解决方案模板
  vm.applySolutionTemplate = function(template) {
    if (confirm('应用此解决方案模板将覆盖当前的解决方案内容，是否继续？')) {
      vm.ticket.resolution = template.content;
      if (template.tags) {
        const templateTags = template.tags.split(',').map(t => t.trim());
        templateTags.forEach(tag => {
          if (vm.selectedTags.indexOf(tag) === -1) {
            vm.selectedTags.push(tag);
          }
        });
      }
    }
  };

  // 提交工单
  vm.submitTicket = function() {
    if (vm.ticketForm.$invalid) {
      alert('请填写必填字段');
      return;
    }

    vm.isLoading = true;

    // 准备提交数据
    const ticketData = angular.copy(vm.ticket);
    ticketData.tags = vm.selectedTags;
    
    // 清理空值
    Object.keys(ticketData).forEach(key => {
      if (ticketData[key] === '' || ticketData[key] === null) {
        delete ticketData[key];
      }
    });

    HttpService.post('/tickets', ticketData)
      .then(response => {
        if (response.success) {
          alert('工单创建成功！工单号：' + response.data.ticket_number);
          clearDraftData();
          vm.resetForm();
          $state.go('app.ticketQuery');
        } else {
          alert('工单创建失败：' + response.message);
        }
      })
      .catch(error => {
        alert('工单创建失败：' + (error.message || '网络错误'));
      })
      .finally(() => {
        vm.isLoading = false;
      });
  };

  // 重置表单
  vm.resetForm = function() {
    vm.ticket = {
      title: '',
      description: '',
      source_url: '',
      source_type: 'web',
      resolution: '',
      location: '',
      ci_item_id: null,
      product_id: null,
      product_module_id: null,
      application_id: null,
      module_id: null,
      product_category_id: null,
      incident_level: 'medium',
      impact_scope: 'individual',
      urgency: 'medium',
      business_impact: '',
      workaround: '',
      ticket_type: 'incident',
      priority: 'medium',
      category: '',
      support_staff_id: null,
      due_date: '',
      estimated_hours: null,
      tags: []
    };
    vm.selectedTags = [];
    vm.tagInput = '';
    vm.activeTab = 'basic';
    vm.availableModules = [];
    
    if (vm.ticketForm) {
      vm.ticketForm.$setPristine();
      vm.ticketForm.$setUntouched();
    }
  };

  vm.cancel = function() {
    if (confirm('确定要取消创建工单吗？未保存的数据将丢失。')) {
      clearDraftData();
      vm.resetForm();
      $state.go('app.home');
    }
  };

  // 监听表单变化，自动保存草稿
  vm.$doCheck = function() {
    if (!vm.isLoading && !vm.isLoadingOptions) {
      saveDraftData();
    }
  };
};

const ticketCreateComponent = {
  templateUrl: 'src/app/pages/ticket-create/ticket-create.template.html',
  controller: ticketCreateController
};

function initTicketCreateController() {
  const angular = window.angular;
  
  if (!angular) {
    console.error('Angular 未找到，无法初始化工单创建控制器模块');
    return;
  }

  angular.module('app.pages.ticketCreate', [])
    .component('ticketCreatePage', ticketCreateComponent);
}

// Listen for vendor libs loaded event
window.addEventListener('vendorLibsLoaded', () => {
  initTicketCreateController();
});

// If Angular already loaded, init directly  
if (window.angular) {
  initTicketCreateController();
}